import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { Config } from '../types/config';
import { getConfig } from '../utils/configStorage';

interface ConfigContextValue {
  config: Config;
  refreshConfig: () => void;
}

const ConfigContext = createContext<ConfigContextValue | undefined>(undefined);

export const ConfigProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [config, setConfig] = useState<Config>(getConfig());

  const refreshConfig = () => {
    setConfig(getConfig());
  };

  useEffect(() => {
    refreshConfig();
    const interval = setInterval(refreshConfig, 5000);
    return () => clearInterval(interval);
  }, []);

  return <ConfigContext.Provider value={{ config, refreshConfig }}>{children}</ConfigContext.Provider>;
};

export const useConfig = (): ConfigContextValue => {
  const context = useContext(ConfigContext);
  if (!context) {
    throw new Error('useConfig must be used within a ConfigProvider');
  }
  return context;
};

